"""
The MainKit provides a base class for executable modules.
"""
import sys
import optparse
import fimero.core.util.OptionKit as OptionKit

class TMain(object):
    """
    TMain is a base class that should be extended by any class that is intended
    to be executed.
    """
    def _execute(self, options, args):        
        """
        Override in base class to execute.
        
        Keyword arguments:
        options -- map of { name : value } for cli options
        args -- list of arguments passed to program
        """
        pass

    def _make_option_parser(self):
        """
        Return an option parser.
        
        This method must be overridden to produce a customized option parser
        
        e.g.
        parser = OptionKit.parse(__doc___)
        
        choices = ["red", "green", "blue"]        
        OptionKit.restrict_option(parser.get_option("-o"), choices)
        
        parser.get_option("-2").default = "mydefault"
        return parser        
        """
        return optparse.OptionParser()
        
    def _backup(self, node):
            backup_file = repr(node.get_path()) + "." + str(time.time()) + ".bak"
            node.rename(backup_file)

    def __init__(self):
        """
        default constructor that sets self.arg_list to None
        """        
        self.arg_list = None

    def interact(self, option_parser):        
        """
        iterates over all options in option_parser option_list and prompts user
        for input. Also queries for contents of self.arg_list.
        
        Keyword arguments:
        option_parser -- customized option parser
        """

        # we slice this array because the first two options are "help" and 
        # "interactive"        
        return OptionKit.prompt_option_list(option_parser.option_list[2:], 
                                     option_parser.values, self.arg_list)


    def main(self, argv=None):
        """
        main method to be executed -- provides programmatic access.
        
        Keyword arguments:
        argv -- argument values; set to sys.argv if None
        """
        if argv is None:
            argv = sys.argv

        parser = self._make_option_parser()
        options, args = parser.parse_args(argv)

        
        if options.interact:            
            interactive_args = self.interact(parser)
            args = args + interactive_args

        self._execute(options, args)
